src = $(wildcard src/*.c)
obj = $(src:.c=.o)
dep = $(obj:.o=.d)

abi = 0
rev = 5

lib_a = $(name).a
sodir = lib

sys := $(shell uname -s | sed 's/MINGW.*/mingw/')
ifeq ($(sys), Darwin)
	lib_so = $(name).dylib
	sharedopt = -dynamiclib

	libgl = -framework OpenGL

else ifeq ($(sys), mingw)
	lib_so = $(name).dll
	sharedopt = -shared
	sodir = bin

	libgl = -lopengl32 -lglu32

else
	soname = $(name).so.$(abi)
	lib_so = $(soname).$(rev)
	ldname = $(name).so
	sharedopt = -shared -Wl,-soname,$(soname)

	libgl = -lGL -lGLU
endif

CFLAGS = -pedantic -Wall $(opt) $(dbg) -fPIC -fcommon -I$(PREFIX)/include $(ft2_cflags) -DUSE_THREADS
LDFLAGS = -L$(PREFIX)/lib $(ft2_libs) $(libgl) -lpthread

.PHONY: all
all: $(lib_a) $(lib_so) $(soname) $(ldname)

$(lib_a): $(obj)
	$(AR) rcs $@ $(obj)

$(lib_so): $(obj)
	$(CC) $(sharedopt) -o $@ $(obj) $(LDFLAGS)
	[ -n "$(ldname)" ] && \
		rm -f $(soname) && ln -s $(lib_so) $(soname) && \
		rm -f $(ldname) && ln -s $(soname) $(ldname) || \
		true

-include $(dep)

%.d: %.c
	@$(CPP) $(CFLAGS) -MM $< >$@

.PHONY: cleanobj
cleanobj:
	rm -f $(obj)

.PHONY: clean
clean:
	rm -f $(obj) $(lib_a) $(lib_so)

.PHONY: cleandep
cleandep:
	rm -f $(dep)

.PHONY: install
install: $(lib_a) $(lib_so)
	mkdir -p $(DESTDIR)$(PREFIX)/bin $(DESTDIR)$(PREFIX)/lib $(DESTDIR)$(PREFIX)/include
	cp $(lib_a) $(DESTDIR)$(PREFIX)/lib/$(lib_a)
	cp $(lib_so) $(DESTDIR)$(PREFIX)/$(sodir)/$(lib_so)
	cp src/drawtext.h $(DESTDIR)$(PREFIX)/include/drawtext.h
	[ -n "$(ldname)" ] && \
		rm -f $(DESTDIR)$(PREFIX)/$(sodir)/$(ldname) $(DESTDIR)$(PREFIX)/$(sodir)/$(soname) && \
		cd $(DESTDIR)$(PREFIX)/lib && ln -s $(lib_so) $(ldname) && ln -s $(lib_so) $(soname) || true


.PHONY: uninstall
uninstall:
	rm -f $(DESTDIR)$(PREFIX)/include/drawtext.h
	rm -f $(DESTDIR)$(PREFIX)/lib/$(lib_a)
	rm -f $(DESTDIR)$(PREFIX)/$(sodir)/$(lib_so)
	[ -n "$(ldname)" ] && \
		rm -f $(DESTDIR)$(PREFIX)/$(sodir)/$(ldname) && \
		rm -f $(DESTDIR)$(PREFIX)/$(sodir)/$(soname) || true


.PHONY: both
both:
	./configure --disable-freetype
	$(MAKE) cleanobj
	$(MAKE)
	./configure --enable-freetype
	$(MAKE) cleanobj
	$(MAKE)

.PHONY: both-install
both-install:
	./configure --disable-freetype
	$(MAKE) cleanobj
	$(MAKE) install
	./configure --enable-freetype
	$(MAKE) cleanobj
	$(MAKE) install
	$(MAKE) cleanobj
